﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using IdleTest.EFAndMVCDemo.IServices;
using IdleTest.EFAndMVCDemo.Models;

namespace IdleTest.EFAndMVCDemo.MvcUI
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    public sealed class AdultRoleAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            IIdentity identity = filterContext.HttpContext.User.Identity;
            var loginResult = new RedirectResult("/User/Login");
            if (string.IsNullOrEmpty(identity.Name) || !identity.IsAuthenticated)
            {                
                filterContext.Result = loginResult;
                return;
            }

            UserModel model = IocContainer.Instance<IUserService>().GetModel(identity.Name);
            if (model == null)
            {
                filterContext.Result = loginResult;
            }
            else if (model.Age < 18)
            {
                filterContext.Result = GetNotAdultView();
            }
        }

        public ActionResult GetNotAdultView()
        {
            ContentResult result = new ContentResult();
            result.Content = "本页面内容需满18岁才能观看，请您长大后再来访问!";
            return result;
        }
    }
}